import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect, useRef } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig, DomEditor, Boot, createEditor } from '@wangeditor/editor'
import ctrlEnterModule from '@wangeditor/plugin-ctrl-enter'
import { message } from 'antd'

function MyEditor(props) {
    //注册更换为ctrl+enter换位
    // Boot.registerModule(ctrlEnterModule)
    // console.log(props,'props');

    const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));

    const {
        value,
        getHtmlContent,
        clear,
        setClear,
        sendPrivateMessage,
        setFull,
        isFull,
        // onRef
    } = props
    // editor 实例
    // const [editor, setEditor] = useState<IDomEditor | null>(null)   // TS 语法
    const [editor, setEditor] = useState(null)                   // JS 语法
    const [text, setText] = useState('');
    // 编辑器内容
    const [html, setHtml] = useState('');
    useEffect(() => {
        if (editor) {
            editor.on('fullScreen', () => { console.log('fullScreen'); setFull(true) })
            editor.on('unFullScreen', () => { console.log('unFullScreen'); setFull(false) })
            // editor.insertBreak =(event)=>{
            //     console.log('123456op',event);
            // }

        }
    }, [editor])



    //查看当前工具栏及其排序
    function onChange(editor) {
        const toolbar = DomEditor.getToolbar(editor)
    }

    // 工具栏配置
    // const toolbarConfig: Partial<IToolbarConfig> = { }  // TS 语法
    const toolbarConfig = {}     // JS 语法
    //排除部分菜单
    toolbarConfig.excludeKeys = [
        "headerSelect",
        "blockquote",
        "|",
        "bold",
        "underline",
        "italic",
        "color",
        "bgColor",
        "|",
        "fontSize",
        "fontFamily",
        "lineHeight",
        "|",
        "bulletedList",
        "numberedList",
        "todo",
        // "emotion",
        "insertLink",
        'group-image',
        'group-video',
        "insertTable",
        "codeBlock",
        "divider",
        "|",
        "undo",
        "redo",
        "|",
        // 'headerSelect',
        'group-more-style', // 排除菜单组，写菜单组 key 的值即可
        "group-justify",
        "group-indent",
    ]

    // 编辑器配置
    // const editorConfig: Partial<IEditorConfig> = {    // TS 语法
    const editorConfig = {                         // JS 语法
        placeholder: '请输入消息…',
        MENU_CONF: {},
    }
    // console.log('editorConfig', editorConfig);

    //最大可输入字符数
    editorConfig.maxLength = 500;
    // editorConfig.onMaxLength = function (editor: IDomEditor) {   // TS 语法
    editorConfig.onMaxLength = function (editor) {            // JS 语法
        // 当达到 maxlength 限制时，触发该回调函数
        message.warn('不能超过500字符数！')
    }

    editorConfig.MENU_CONF['lineHeight'] = {
        lineHeightList: ['1', '1.5', '2', '2.5']
    }
    // 回车发送消息,ctrl+回车换行start
    let handleKeyDown;

    const attachKeyDownListener = (editor) => {
        handleKeyDown = (event) => {
            if (event.keyCode === 13 && !event.ctrlKey) {
                if (!editor.getText() || editor.getHtml() == '<p><br></p>') return
                event.preventDefault();
                sendPrivateMessage();
                setEditor(null);
            } else if (event.keyCode === 13 && event.ctrlKey) {
                event.preventDefault();
                editor.insertBreak(); // 调用 insertBreak 方法
            }
        };

        document.addEventListener('keydown', handleKeyDown);
    };

    const detachKeyDownListener = () => {
        document.removeEventListener('keydown', handleKeyDown);
    };
    editorConfig.onFocus = (editor) => {
        attachKeyDownListener(editor);
    };
    editorConfig.onBlur = (editor) => {
        detachKeyDownListener();
        // editor blur
    };

    // 回车发送消息,ctrl+回车换行end

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])
    //初始值
    useEffect(() => {
        if (value) {
            setHtml(value)
        } else {
            setHtml('')
        }
        // if (clear == true) {
        //     // setHtml('');
        //     if (editor) {
        //         // editor.blur()
        //         // console.log('asdghjkl');
        //         editor.disable()
        //     }
        //     if (editor) {
        //         setTimeout(() => {
        //             editor.enable()
        //         }, 1000);
        //     }
        //     setTimeout(() => {
        //         // if (editor) {
        //         //     editor.restoreSelection()
        //         // }
        //         setClear();
        //     }, 10);
        // }
    }, [value, clear, setClear])

    // 自定义校验链接
    // function customCheckLinkFn(text: string, url: string): string | boolean | undefined {   // TS 语法
    function customCheckLinkFn(text, url) {                                              // JS 语法

        if (!url) {
            return
        }
        if (url.indexOf('http') !== 0) {
            return '链接必须以 http/https 开头'
        }
        return true

        // 返回值有三种选择：
        // 1. 返回 true ，说明检查通过，编辑器将正常插入链接
        // 2. 返回一个字符串，说明检查未通过，编辑器会阻止插入。会 alert 出错误信息（即返回的字符串）
        // 3. 返回 undefined（即没有任何返回），说明检查未通过，编辑器会阻止插入。但不会提示任何信息
    }

    // 自定义转换链接 url
    // function customParseLinkUrl(url: string): string {   // TS 语法
    function customParseLinkUrl(url) {                // JS 语法

        if (url.indexOf('http') !== 0) {
            return `http://${url}`
        }
        return url
    }

    // 插入链接
    editorConfig.MENU_CONF['insertLink'] = {
        checkLink: customCheckLinkFn, // 也支持 async 函数
        parseLinkUrl: customParseLinkUrl, // 也支持 async 函数
    }
    // 更新链接
    editorConfig.MENU_CONF['editLink'] = {
        checkLink: customCheckLinkFn, // 也支持 async 函数
        parseLinkUrl: customParseLinkUrl, // 也支持 async 函数
    }
    editorConfig.MENU_CONF['emotion'] = {
        emotions: '😃 😄 😁 😆 😅 😂 😊 😇 😉 😌 😍 😘 😚 😋 😝 😜 😎 😏 😒 😞 😔 😣 😖 😫 😩 😢 😭 😤 😠 😡 😳 😱 😨 😶 😷 😈 💩 👻 💀 👀 👣 👐 🙌 👏 👍 👎 👊 ✊ ✌️ 👌 👈 👉 👆 👇 ☝️ ✋ 👋 💪 ✍️ 🙏 '.split(' '),// 数组
        type: 'emoji',
    }

    //插入图片
    editorConfig.MENU_CONF['uploadImage'] = {
        server: window._chatBasicProxy + 'api/commons/file/batch/upload',
        // server: '/api/upload-img-10s', // test timeout
        // server: '/api/upload-img-failed', // test failed
        // server: '/api/xxx', // test 404

        timeout: 5 * 1000, // 5s

        fieldName: 'files',
        allowedFileTypes: ['image/*'],
        meta: { modelName: "chat-" + userInfo.userId, sysId: '460' },
        metaWithUrl: false, // join params to url
        // headers: { Accept: 'text/x-json' },
        headers: { Accept: '*/*', Authorization: sessionStorage.getItem('token') },

        maxFileSize: 10 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

        onBeforeUpload(file) {
            // console.log('onBeforeUpload', file,)

            return file // will upload this file
            // return false // prevent upload
        },
        onProgress(progress) {
            // console.log('onProgress', progress)
        },
        onSuccess(file, res) {
            // console.log('onSuccess', file, res)
        },
        onFailed(file, res) {
            // alert(res.message)
            // console.log('onFailed1111', file, res)
        },
        onError(file, err, res) {
            // alert(err.message)
            // console.error('onError', file, err, res)
        },

        customInsert(res, insertFn) {
            //   console.log('customInsert', res)
            const imgInfo = res.data[0] || {}
            const { url, alt, href } = imgInfo
            if (!url) throw new Error(`Image url is empty`)

            //   console.log('Your image url ', url)
            insertFn(url.replace(/ /g, ""), alt, href)
        },
    }
    //插入视频
    editorConfig.MENU_CONF['insertVideo'] = {
        onInsertedVideo(videoNode) {
            //   console.log('inserted video', videoNode)
        },
    }
    //上传视频
    editorConfig.MENU_CONF['uploadVideo'] = {
        server: window._noticeBasicProxy + '/api/commons/file/batch/upload',
        // server: '/api/upload-img-failed', // test failed
        // server: '/api/xxx', // test 404

        timeout: 5 * 1000, // 5s

        fieldName: 'files',
        meta: { modelName: "chat-" + userInfo.userId, sysId: '460' },
        metaWithUrl: false, // join params to url
        headers: { Accept: '*/*', Authorization: sessionStorage.getItem('token') },

        maxFileSize: 10 * 1024 * 1024, // 10M

        onBeforeUpload(file) {
            //   console.log('onBeforeUpload', file)

            return file // will upload this file
            // return false // prevent upload
        },
        onProgress(progress) {
            //   console.log('onProgress', progress)
        },
        onSuccess(file, res) {
            //   console.log('onSuccess', file, res)
        },
        onFailed(file, res) {
            //   alert(res.message)
            //   console.log('onFailed', file, res)
        },
        onError(file, err, res) {
            //   alert(err.message)
            //   console.error('onError', file, err, res)
        },

        customInsert(res, insertFn) {
            //   console.log('customInsert', res)
            const videoInfo = res.data[0] || {}
            const { url, poster } = videoInfo
            if (!url) throw new Error(`Video url is empty`)

            //   console.log('Your video url ', url)
            insertFn(url, poster)
        },
    }
    return (
        <>
            <div style={{ borderTop: '1px solid #c3ddf1', zIndex: 10, width: '100%', borderRadius: '0 0 8px 0' }}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                // style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    onChange={(editor, e) => { setHtml(editor.getHtml()); setText(editor.getText()); getHtmlContent(editor.getHtml()); onChange(editor, e) }}
                    // onChange={editor => { setHtml(editor.getHtml()); getHtmlContent(editor.getHtml()); }}
                    mode="default"
                    style={{ height: '129px', overflowY: 'hidden' }}
                />
            </div>
            {/* <div style={{ marginTop: '15px' }}>
                {html}
            </div> */}
        </>
    )
}

export default MyEditor